import React, { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout'
import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Image } from 'antd';
import MusicAPI from '@/services/ant-design-pro/music';
import ProTable from '@ant-design/pro-table';
import m_config from '@/config/config'
import CreateOrEdit from './components/CreateOrEdit'

const { getCarousel, deleteCarousel } = MusicAPI;
const Carousel = (props) => {
    const actionRef = useRef(); // 表格ref，便于自定义操作表格
    const [isModalVisible, setIsModalVisible] = useState(false),
        [editData, setEditData] = useState(undefined),
        [data, setData] = useState([]);

    /**
     * 设置轮播图数据到state
     * @returns obj(轮播图列表)
     */
    const setCarousel = async () => {
        const result = await getCarousel();
        setData(result.data.value);
        return {
            data: result.data.value,
            success: true
        }
    }

    /**
     * 控制模态框显示与隐藏
     */
    const isShowModal = (show, record = undefined) => {
        setIsModalVisible(show);
        setEditData(record);
    };

    const delCarousel = async (record) => {
        const result = await deleteCarousel({
            carousel_id: record.carousel_id
        })
        if (result.status == 'ok') {
            await setCarousel();
            actionRef.current.reload();
            message.success("删除成功");
        } else {
            message.error('删除失败：' + result.data.message);
            console.log(result.data.error);
        }
    }

    /**
     * 获取轮播图列表
     * @param {obj} params 搜索参数
     * @returns obj(轮播图列表)
     */
    const getData = (params) => {
        if (JSON.stringify(data) != "[]") {
            let name = params.name || "",
                category = params.category || "",
                result = data;
            if (name.trim().length > 0 || category) {
                result = data.filter((item, index) => {
                    if (name && category) {
                        return item.name.toLowerCase().indexOf(name.toLowerCase()) >= 0
                            && item.category == category
                    } else if (name) {
                        return item.name.toLowerCase().indexOf(name.toLowerCase()) >= 0
                    } else if (category) {
                        return item.category == category;
                    }
                })
            }
            return {
                data: result,
                success: true
            }
        }
        return setCarousel();
    }

    const columns = [
        {
            dataIndex: 'index',
            valueType: 'indexBorder',
            width: 48,
        },
        {
            title: '图片',
            dataIndex: 'carousel_id',
            filters: true,
            onFilter: true,
            hideInSearch: true,
            render: (text, record, _, action) => [
                <Image
                    key={record.carousel_id}
                    height={100}
                    src={`${m_config.local + record.carousel_file_src + record.carousel_file_name}`}
                />
            ],
        },
        {
            title: '创建时间',
            key: 'create_time',
            dataIndex: 'create_time',
            valueType: 'dateTime',
            sorter: true,
            hideInSearch: true,
        },
        {
            title: '操作',
            valueType: 'option',
            render: (text, record, _, action) => [
                <a key="editable" onClick={() => isShowModal(true, record)}>
                    编辑
                </a>,
                <a rel="noopener noreferrer" key="del" onClick={() => delCarousel(record)}>
                    删除
                </a>,
            ],
        },
    ];

    return (
        <PageContainer>
            <ProTable columns={columns} actionRef={actionRef} request={(params = {}, sort, filter) => {
                return getData(params);
            }}
                rowKey="carousel_id"
                search={false} pagination={{
                    pageSize: 5,
                }} dateFormatter="string" headerTitle="高级表格" toolBarRender={() => [
                    <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => isShowModal(true)}>
                        新建
                    </Button>,
                ]} />
            {
                isModalVisible ?
                    <CreateOrEdit
                        isModalVisible={isModalVisible}
                        isShowModal={isShowModal}
                        actionRef={actionRef}
                        initData={editData}
                        setData={setCarousel}
                    /> : ""
            }
        </PageContainer>
    )
}

export default Carousel;


